package com.example.system.security.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import org.springframework.security.core.userdetails.UserDetails;

import jakarta.annotation.PostConstruct;
import java.security.Key;
import java.util.Date;

@Component
public class JwtTokenUtil {
    
    private String secret = "your-very-long-secret-key-at-least-32-characters-long";
    
    private long expiration = 86400000;
    
    private Key signingKey;
    
    // 初始化签名Key
    @PostConstruct
    public void init() {
        signingKey = Keys.hmacShaKeyFor(secret.getBytes());
    }
    
    // 生成token
    public String generateToken(UserDetails userDetails) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);
        
        return Jwts.builder()
                   .setSubject(userDetails.getUsername())
                   .setIssuedAt(now)
                   .setExpiration(expiryDate)
                   .signWith(signingKey, SignatureAlgorithm.HS256)
                   .compact();
    }
    
    // 从token中获取用户名
    public String getUsernameFromToken(String token) {
        return parseToken(token).getBody().getSubject();
    }
    
    // 验证token是否有效
    public boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception error) {
            return false;
        }
    }
    
    // 解析token
    private Jws<Claims> parseToken(String token) {
        return Jwts.parserBuilder()
                   .setSigningKey(signingKey)
                   .build()
                   .parseClaimsJws(token);
    }
    
    public long getExpiration() {
        return expiration;
    }
}
